import type { Module } from 'vuex'
import type { IRootState } from '..'

import { eolink } from '@/api'
import { message } from 'ant-design-vue'
import cookie from 'js-cookie'

export interface IEolinkState {
  shareCode: string
  shareID: string
  shareToken: string
  sharePassword: string
}

export const enum MutationTypes {
  setShareCode = 'e_code',
  setShareId = 'e_share_id',
  setShareToken = 'e_share_token',
  setSharePassword = 'e_share_pwd'
}

const SHARE_CODE = new URLSearchParams(location.search.replace(/^\?/, '')).get('shareCode') || import.meta.env.VITE_EOLINK_SHARE_CODE_YC

export default {
  namespaced: true,
  state: {
    // =========== 项目属性 ==============
    shareCode: SHARE_CODE,
    shareID: '',
    shareToken: document.cookie,
    sharePassword: import.meta.env.VITE_EOLINK_PWD1
    // ========== 业务模板配置 ============
  },

  mutations: {
    [MutationTypes.setShareCode](state, payload) {
      state.shareCode = payload
    },
    [MutationTypes.setShareId](state, payload) {
      state.shareID = payload
    },
    [MutationTypes.setShareToken](state, payload) {
      state.shareToken = payload
    },
    [MutationTypes.setSharePassword](state, payload) {
      state.sharePassword = payload
    }
  },
  actions: {
    /** 传入 shareCode 修改 */
    async getShareId({ commit, state }, shareCode: string) {
      if (shareCode && shareCode != state.shareCode) {
        commit(MutationTypes.setShareCode, shareCode)
      } else if (state.shareID) {
        return state.shareID
      }
      message.warn('正在获取 project info...')
      const res = await eolink.getProjectInfo({
        shareCode: state.shareCode,
        shareType: 'project'
      })
      // 获取shareId 并更新进入state
      commit(MutationTypes.setShareId, res.shareID)
      return res.shareID
    },
    /** 登录接口， 返回 true 则表示成功 */
    async login({ state, commit, dispatch }): Promise<boolean> {
      try {
        const shareID = await dispatch('getShareId')
        const res2 = await eolink.verifySharePassword({
          shareCode: state.shareCode,
          shareID: `${shareID}`,
          sharePassword: state.sharePassword
        })
        // 设置 cookie
        cookie.set('shareToken', res2.shareToken, {
          expires: 1
        })
        const res3 = await eolink.verifyShareToken({
          shareCode: state.shareCode,
          shareID: `${shareID}`,
          shareToken: res2.shareToken
        })
        if (res3.statusCode != '000000') {
          throw new Error('token校验未通过，可能需要重新获取')
        }
        // 更新 password
        commit(MutationTypes.setShareToken, res2.shareToken)
        return true
      } catch (error) {
        console.error(error)
      }
      return false
    }
  }
} as Module<IEolinkState, IRootState>